package com.thread.config;

import com.thread.service.impl.VisiableThreadPoolTaskExecutor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @Author: 胡成
 * @Version: 0.0.1V
 * @Date: 2018/10/31
 * @Description: 线程池配置
 **/
@Slf4j
@EnableAsync//启用异步
@Configuration
public class ExecutorConfig {

    @Bean
    public Executor asyncExecutor(){
        log.info("start asyncExecutor");
//        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //使用VisiableThreadPoolTaskExecutor
        ThreadPoolTaskExecutor executor = new VisiableThreadPoolTaskExecutor();
        executor.setCorePoolSize(5);
        executor.setMaxPoolSize(5);
        executor.setQueueCapacity(999);
        executor.setThreadNamePrefix("async-service-");
        // rejection-policy：当pool已经达到max size的时候，如何处理新任务
        // CALLER_RUNS：不在新线程中执行任务，而是有调用者所在的线程来执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //初始化线程
        executor.initialize();
        //配置核心线程数
        log.info("end asyncExecutor");
        return executor;
    }
}
